package com.xiaolin.sports.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.xiaolin.sports.common.RspResult;
import com.xiaolin.sports.common.enums.Status;
import com.xiaolin.sports.model.CollectionRecord;
import com.xiaolin.sports.model.ParentInfo;
import com.xiaolin.sports.service.ICollectionService;
import com.xiaolin.sports.service.IParentInfoService;
import com.xiaolin.sports.wechat.model.WechatUserInfo;

@RequestMapping("collection")
@Controller
public class CollectionController extends BaseController {
	
	private Logger logger = LoggerFactory.getLogger(CollectionController.class);
	
	@Autowired
	private ICollectionService collectionService;
	@Autowired
	private IParentInfoService parentInfoService;
	
	@RequestMapping("add")
	@ResponseBody Object add(Integer courseId){
		try {
			WechatUserInfo userInfo = getWechatUserInfo();
			ParentInfo parentInfo = parentInfoService.selectByOpenid(userInfo.getOpenid());
			CollectionRecord record = new CollectionRecord();
			record.setCourseId(courseId);
			record.setParentId(parentInfo.getId());
			CollectionRecord collect = collectionService.selectByParam(record);
			if(collect == null) {
				collectionService.addAndUpdate(record);
			}
			return new RspResult(Status.SUCCESS);
		} catch (Exception e) {
			logger.error("----collection add error={}", e);
		}
		return new RspResult(Status.FAIL);
	}
	
	@RequestMapping("cancel")
	@ResponseBody Object cancel(Integer courseId){
		try {
			WechatUserInfo userInfo = getWechatUserInfo();
			ParentInfo parentInfo = parentInfoService.selectByOpenid(userInfo.getOpenid());
			CollectionRecord record = new CollectionRecord();
			record.setParentId(parentInfo.getId());
			record.setCourseId(courseId);
			record = collectionService.selectByParam(record);
			if(record != null) {
				record.setIsDelete("Y");
				collectionService.addAndUpdate(record);
			}
			return new RspResult(Status.SUCCESS);
		} catch (Exception e) {
			logger.error("----collection cancel error={}", e);
		}
		return new RspResult(Status.FAIL);
	}
	
	@RequestMapping("query")
	@ResponseBody Object query(Integer courseId) {
		WechatUserInfo userInfo = getWechatUserInfo();
		CollectionRecord record = new CollectionRecord();
		ParentInfo parentInfo = parentInfoService.selectByOpenid(userInfo.getOpenid());
		record.setParentId(parentInfo.getId());
		record.setCourseId(courseId);
		record = collectionService.selectByParam(record);
		return record != null ? 1 : 0;
	}
}
